{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lJz6FDU1lRzc"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "\n",
        "## Install dependencies\n",
        "!pip install wget\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install unidecode\n",
        "!pip install matplotlib>=3.3.2\n",
        "\n",
        "## Install NeMo\n",
        "BRANCH = 'main'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "\"\"\"\n",
        "Remember to restart the runtime for the kernel to pick up any upgraded packages (e.g. matplotlib)!\n",
        "Alternatively, you can uncomment the exit() below to crash and restart the kernel, in the case\n",
        "that you want to use the \"Run All Cells\" (or similar) option.\n",
        "\"\"\"\n",
        "# exit()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FGIVHjS1YEPw"
      },
      "source": [
        "# Self-Supervised pre-training for ASR\n",
        "\n",
        "This notebook is a basic tutorial for pre-training a model using the self-supervised approach. With this approach, we use a training objective that does not require our dataset to be labeled, which significantly reduces the difficulty of collecting data for pre-training the model. After pre-training our encoder in this way, we can use it in a CTC or RNNT ASR model.\n",
        "\n",
        "The approach we will use for pre-training our models is represented in the following diagram:\n",
        "\n",
        " ![SSL diagram](https://raw.githubusercontent.com/NVIDIA/NeMo/main/tutorials/asr/images/contrastive_ssl.png)\n",
        "\n",
        "We first mask parts of our input using SpecAugment.  The model is then trained to solve a contrastive task of distinguishing the latent representation of the masked time steps from several sampled distractors. Since our encoders also contain stride blocks which reduce the length of the inputs, in order to obtain target representations we combine several consecutive time steps. They are then passed through a quantizer, which has been found to help with contrastive pre-training."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i5XZWBnTf1pT"
      },
      "source": [
        "# Preparing our data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "38aYTCTIlRzh"
      },
      "source": [
        "## Downloading dataset\n",
        "\n",
        "In order to demonstrate how to pre-train the model, we will use the AN4 dataset. Note: this is dataset is much smaller than one that we would typically want to use for self-supervised training, however it will suffice for this tutorial. This dataset also contains transcriptions, but they will be ignored for self-supervised pre-training.\n",
        "\n",
        "Before we get started, let's download and prepare the dataset. The utterances are available as `.sph` files, so we will need to convert them to `.wav` for later processing. If you are not using Google Colab, please make sure you have [Sox](http://sox.sourceforge.net/) installed for this step--see the \"Downloads\" section of the linked Sox homepage. (If you are using Google Colab, Sox should have already been installed in the setup cell at the beginning.)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gAhsmi6HlRzh"
      },
      "outputs": [],
      "source": [
        "# This is where the an4/ directory will be placed.\n",
        "# Change this if you don't want the data to be extracted in the current directory.\n",
        "data_dir = '.'"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true,
        "id": "Yb4fuUvWlRzk",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "import glob\n",
        "import os\n",
        "import subprocess\n",
        "import tarfile\n",
        "import wget\n",
        "\n",
        "# Download the dataset. This will take a few moments...\n",
        "print(\"******\")\n",
        "if not os.path.exists(data_dir + '/an4_sphere.tar.gz'):\n",
        "    an4_url = 'https://dldata-public.s3.us-east-2.amazonaws.com/an4_sphere.tar.gz'\n",
        "    an4_path = wget.download(an4_url, data_dir)\n",
        "    print(f\"Dataset downloaded at: {an4_path}\")\n",
        "else:\n",
        "    print(\"Tarfile already exists.\")\n",
        "    an4_path = data_dir + '/an4_sphere.tar.gz'\n",
        "\n",
        "if not os.path.exists(data_dir + '/an4/'):\n",
        "    # Untar and convert .sph to .wav (using sox)\n",
        "    tar = tarfile.open(an4_path)\n",
        "    tar.extractall(path=data_dir)\n",
        "\n",
        "    print(\"Converting .sph to .wav...\")\n",
        "    sph_list = glob.glob(data_dir + '/an4/**/*.sph', recursive=True)\n",
        "    for sph_path in sph_list:\n",
        "        wav_path = sph_path[:-4] + '.wav'\n",
        "        cmd = [\"sox\", sph_path, wav_path]\n",
        "        subprocess.run(cmd)\n",
        "print(\"Finished conversion.\\n******\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m_LFeM0elRzm"
      },
      "source": [
        "You should now have a folder called `an4` that contains `etc/an4_train.transcription`, `etc/an4_test.transcription`, audio files in `wav/an4_clstk` and `wav/an4test_clstk`, along with some other files we will not need.\n",
        "\n",
        "Now we can load and take a look at the data. As an example, file `cen2-mgah-b.wav` is a 2.6 second-long audio recording of a man saying the letters \"G L E N N\" one-by-one. To confirm this, we can listen to the file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_M_bSs3MjQlz"
      },
      "outputs": [],
      "source": [
        "import librosa\n",
        "import IPython.display as ipd\n",
        "\n",
        "# Load and listen to the audio file\n",
        "example_file = data_dir + '/an4/wav/an4_clstk/mgah/cen2-mgah-b.wav'\n",
        "audio, sample_rate = librosa.load(example_file)\n",
        "\n",
        "ipd.Audio(example_file, rate=sample_rate)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RdNyw1b_zgtm"
      },
      "source": [
        "## Creating Data Manifests\n",
        "\n",
        "The first thing we need to do now is to create manifests for our training and evaluation data, which will contain the metadata of our audio files. NeMo data sets take in a standardized manifest format where each line corresponds to one sample of audio, such that the number of lines in a manifest is equal to the number of samples that are represented by that manifest. \n",
        "\n",
        "\n",
        "A line must contain the path to an audio file, and the duration of the audio sample. For labeled datasets it will also contain the corresponding transcript (or path to a transcript file). Even though for self-supervised pre-training the transcript is unnecessary, we will still add it to our manifest, since we will also be using this dataset to demonstrate fine-tuning later on.\n",
        "\n",
        "Here's an example of what one line in a NeMo-compatible manifest might look like:\n",
        "```\n",
        "{\"audio_filepath\": \"path/to/audio.wav\", \"duration\": 3.45, \"text\": \"this is a nemo tutorial\"}\n",
        "```\n",
        "\n",
        "We can build our training and evaluation manifests using `an4/etc/an4_train.transcription` and `an4/etc/an4_test.transcription`, which have lines containing transcripts and their corresponding audio file IDs:\n",
        "```\n",
        "...\n",
        "<s> P I T T S B U R G H </s> (cen5-fash-b)\n",
        "<s> TWO SIX EIGHT FOUR FOUR ONE EIGHT </s> (cen7-fash-b)\n",
        "...\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lVB1sG1GlRzz"
      },
      "outputs": [],
      "source": [
        "# --- Building Manifest Files --- #\n",
        "import json\n",
        "\n",
        "# Function to build a manifest\n",
        "def build_manifest(transcripts_path, manifest_path, wav_path):\n",
        "    with open(transcripts_path, 'r') as fin:\n",
        "        with open(manifest_path, 'w') as fout:\n",
        "            for line in fin:\n",
        "                # Lines look like this:\n",
        "                # <s> transcript </s> (fileID)\n",
        "                transcript = line[: line.find('(')-1].lower()\n",
        "                transcript = transcript.replace('<s>', '').replace('</s>', '')\n",
        "                transcript = transcript.strip()\n",
        "\n",
        "                file_id = line[line.find('(')+1 : -2]  # e.g. \"cen4-fash-b\"\n",
        "                audio_path = os.path.join(\n",
        "                    data_dir, wav_path,\n",
        "                    file_id[file_id.find('-')+1 : file_id.rfind('-')],\n",
        "                    file_id + '.wav')\n",
        "\n",
        "                duration = librosa.core.get_duration(filename=audio_path)\n",
        "\n",
        "                # Write the metadata to the manifest\n",
        "                metadata = {\n",
        "                    \"audio_filepath\": audio_path,\n",
        "                    \"duration\": duration,\n",
        "                    \"text\": transcript\n",
        "                }\n",
        "                json.dump(metadata, fout)\n",
        "                fout.write('\\n')\n",
        "                \n",
        "# Building Manifests\n",
        "print(\"******\")\n",
        "train_transcripts = data_dir + '/an4/etc/an4_train.transcription'\n",
        "train_manifest = data_dir + '/an4/train_manifest.json'\n",
        "if not os.path.isfile(train_manifest):\n",
        "    build_manifest(train_transcripts, train_manifest, 'an4/wav/an4_clstk')\n",
        "    print(\"Training manifest created.\")\n",
        "\n",
        "test_transcripts = data_dir + '/an4/etc/an4_test.transcription'\n",
        "test_manifest = data_dir + '/an4/test_manifest.json'\n",
        "if not os.path.isfile(test_manifest):\n",
        "    build_manifest(test_transcripts, test_manifest, 'an4/wav/an4test_clstk')\n",
        "    print(\"Test manifest created.\")\n",
        "print(\"***Done***\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FLr1aJ-lf4_7"
      },
      "source": [
        "# Self-supervised pre-training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sT_uewIDk8oA"
      },
      "source": [
        "## Setting up the config\n",
        "\n",
        "First, let's download the default config for ssl pre-training of Citrinet-1024, and the corresponding supervised training config, which we will use for fine-tuning later."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "978wWK7AKIvU"
      },
      "outputs": [],
      "source": [
        "## Grab the configs we'll use in this example\n",
        "!mkdir configs\n",
        "!wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/asr/conf/ssl/citrinet/citrinet_ssl_1024.yaml\n",
        "!wget -P configs/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/examples/asr/conf/citrinet/citrinet_1024.yaml\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RLzjCgmHuJ_j"
      },
      "source": [
        "Since this config is for a very large model, we will modify it to make a much smaller version for the purpose of this tutorial by reducing the number of channels and the number of sub-blocks in each block."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Vmw9WbTPKHHA"
      },
      "outputs": [],
      "source": [
        "from omegaconf import OmegaConf\n",
        "import torch\n",
        "\n",
        "config_path = data_dir + '/configs/citrinet_ssl_1024.yaml'\n",
        "\n",
        "cfg = OmegaConf.load(config_path)\n",
        "\n",
        "cfg.model.model_defaults.filters = 256\n",
        "cfg.model.model_defaults.repeat = 1\n",
        "cfg.model.model_defaults.enc_final = 256\n",
        "\n",
        "cfg.model.train_ds.manifest_filepath = train_manifest\n",
        "cfg.model.train_ds.batch_size = 16\n",
        "\n",
        "cfg.model.validation_ds.manifest_filepath = test_manifest\n",
        "cfg.model.validation_ds.batch_size = 16\n",
        "\n",
        "cfg.trainer.max_epochs = None\n",
        "cfg.trainer.devices = 1\n",
        "cfg.trainer.max_steps = 10000 \n",
        "#in practice you will usually want a much larger amount of pre-training steps\n",
        "cfg.trainer.log_every_n_steps = 100\n",
        "\n",
        "if torch.cuda.is_available():\n",
        "  cfg.trainer.accelerator = 'gpu'\n",
        "  cfg.trainer.strategy = 'dp'\n",
        "  cfg.trainer.gpus = 1\n",
        "else:\n",
        "  cfg.trainer.accelerator = 'cpu'\n",
        "  cfg.trainer.strategy = None\n",
        "  cfg.trainer.gpus = 0\n",
        "\n",
        "cfg.exp_manager.exp_dir = data_dir + \"/content/exp\"\n",
        "cfg.exp_manager.name = \"pre_trained\"\n",
        "cfg.exp_manager.use_datetime_version = False\n",
        "cfg.exp_manager.create_tensorboard_logger = False\n",
        "cfg.exp_manager.resume_if_exists = True\n",
        "cfg.exp_manager.resume_ignore_no_checkpoint = True\n",
        "cfg.exp_manager.checkpoint_callback_params.save_best_model = True\n",
        "\n",
        "cfg.trainer.check_val_every_n_epoch = 1\n",
        "\n",
        "cfg.model.optim.sched.name = \"CosineAnnealing\"\n",
        "cfg.model.optim.sched.warmup_steps = 1000\n",
        "cfg.model.optim.sched.max_steps = 5000\n",
        "#in practice you will usually want a much larger amount of pre-training steps\n",
        "cfg.model.optim.sched.min_lr = 0\n",
        "cfg.model.optim.lr = 0.015\n",
        "cfg.model.optim.weight_decay = 0\n",
        "\n",
        "cfg.trainer.max_steps = cfg.model.optim.sched.max_steps\n",
        "\n",
        "cfg.model.spec_augment.patch_size = 16\n",
        "\n",
        "cfg.model.train_ds.min_duration = 2\n",
        "cfg.model.validation_ds.min_duration = 2\n",
        "#with patch_size set to 16 and 10 patches, \n",
        "#we need to be able to mask 160 time steps;\n",
        "#at preprocessor stride 0.01 this means we need minimum duration of 1.6 seconds \n",
        "#or more to sample only from masked steps in the same utterance\n",
        "\n",
        "cfg.model.loss.num_negatives = 40"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TrfAb1DjWzpL"
      },
      "source": [
        "The following parameters will be used for decoder, loss, and masking:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DTcn93gMXQba"
      },
      "outputs": [],
      "source": [
        "print(OmegaConf.to_yaml(cfg.model.decoder))\n",
        "print(OmegaConf.to_yaml(cfg.model.loss))\n",
        "print(OmegaConf.to_yaml(cfg.model.spec_augment))"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Note that for this loss the outputs must match the inputs, so since we are using Citrinet architecture with 8x stride, we would need to either set \"cfg.model.loss.combine_time_steps\" to 8, or put additional stride layers in the decoder. By default for Citrinet with 8x stride we use \"cfg.model.loss.combine_time_steps=4\" and \"cfg.model.decoder.stride_layers=1\" to match the 8x stride.\n",
        "\n",
        "Since in MaskedPatchAugmentation we set patch_size to 16 and mask_patches is set to 10, this will result in 160 total masked steps in the spectrogram. Since combine_time_steps is set to 4, this means that 160 / 4 = 40 total potential negative can be used, so we set loss.num_negatives to 40 (unless you set sample_from_same_utterance_only to false or sample_from_non_masked to true, but this tends to make results worse).\n",
        "\n",
        "In the default configs we assume that min_duration for samples is higher (8 seconds by default), so there we can set patch_size to 48 for a total of 480 masked steps, and use 100 sampled negatives. If the min_duration of samples that you are training on allows, the amount of masked steps as well as negatives can be increased further (masking around 50% of the sample duration tends to work well)."
      ],
      "metadata": {
        "id": "4JnepitBZ3ta"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yoUIMS7mgrUs"
      },
      "source": [
        "Now we can create the config object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "l0IqI0Yugqc1"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.to_container(cfg, resolve=True)\n",
        "cfg = OmegaConf.create(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OxxEwR05XatQ"
      },
      "source": [
        "## Pre-training the model\n",
        "\n",
        "We can now create the model based on our config and start pre-training with pytorch lightning. In NeMo you can use the examples/asr/speech_pretraining/speech_pre_training.py script for this, which contains the following lines:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WbnVpz03Jxto"
      },
      "outputs": [],
      "source": [
        "import pytorch_lightning as pl\n",
        "from omegaconf import OmegaConf\n",
        "\n",
        "from nemo.collections.asr.models.ssl_models import SpeechEncDecSelfSupervisedModel\n",
        "from nemo.core.config import hydra_runner\n",
        "from nemo.utils import logging\n",
        "from nemo.utils.exp_manager import exp_manager\n",
        "\n",
        "trainer = pl.Trainer(**cfg.trainer)\n",
        "exp_manager(trainer, cfg.get(\"exp_manager\", None))\n",
        "asr_model = SpeechEncDecSelfSupervisedModel(cfg=cfg.model, trainer=trainer)\n",
        "\n",
        "trainer.fit(asr_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FylnQvwvKIy9"
      },
      "source": [
        "# Fine-tuning with pre-trained encoder"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RvhsJbsiKNj6"
      },
      "source": [
        "Now that we have pre-trained our encoder, we can fine-tune our model with a supervised objective. Normally the dataset used for pre-training will be large and unlabeled, while the one used for fine-tuning will be a smaller labeled dataset. For the purpose of this tutorial we will just use the same dataset for fine-tuning."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rk7uDmuHAD2e"
      },
      "source": [
        "## Building tokenizer"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9WsIHRVVADZu"
      },
      "outputs": [],
      "source": [
        "!mkdir scripts\n",
        "!wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/tokenizers/process_asr_text_tokenizer.py\n",
        "\n",
        "!python ./scripts/process_asr_text_tokenizer.py \\\n",
        "  --manifest=\"{data_dir}/an4/train_manifest.json\" \\\n",
        "  --data_root=\"{data_dir}/tokenizers/an4/\" \\\n",
        "  --vocab_size=128 \\\n",
        "  --tokenizer=\"spe\" \\\n",
        "  --no_lower_case \\\n",
        "  --spe_type=\"unigram\" \\\n",
        "  --log"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Na0iuLoQMfgj"
      },
      "source": [
        "## Creating config for fine-tuning with CTC objective\n",
        "\n",
        "We will now create a config for a ctc-based model with a matching encoder to the model we pre-trained."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tzF8uOWOoqeO"
      },
      "outputs": [],
      "source": [
        "config_path = data_dir + '/configs/citrinet_1024.yaml'\n",
        "\n",
        "cfg = OmegaConf.load(config_path)\n",
        "\n",
        "cfg.model.model_defaults.filters = 256\n",
        "cfg.model.model_defaults.repeat = 1\n",
        "cfg.model.model_defaults.enc_final = 256\n",
        "\n",
        "cfg.model.spec_augment.freq_masks = 2\n",
        "cfg.model.spec_augment.time_masks = 5\n",
        "\n",
        "cfg.model.train_ds.manifest_filepath = train_manifest\n",
        "cfg.model.train_ds.batch_size = 16\n",
        "\n",
        "cfg.model.validation_ds.manifest_filepath = test_manifest\n",
        "cfg.model.validation_ds.batch_size = 16\n",
        "\n",
        "cfg.model.log_prediction = False\n",
        "\n",
        "cfg.trainer.max_epochs = None\n",
        "cfg.trainer.devices = 1\n",
        "cfg.trainer.max_steps = 2000 \n",
        "\n",
        "if torch.cuda.is_available():\n",
        "  cfg.trainer.accelerator = 'gpu'\n",
        "  cfg.trainer.strategy = 'dp'\n",
        "  cfg.trainer.gpus = 1\n",
        "else:\n",
        "  cfg.trainer.accelerator = 'cpu'\n",
        "  cfg.trainer.strategy = None\n",
        "  cfg.trainer.gpus = 0\n",
        "\n",
        "cfg.model.tokenizer.dir = data_dir + \"/tokenizers/an4/tokenizer_spe_unigram_v128/\"  # note this is a directory, not a path to a vocabulary file\n",
        "cfg.model.tokenizer.type = \"bpe\"\n",
        "\n",
        "cfg.exp_manager.exp_dir = data_dir + \"/content/exp\"\n",
        "cfg.exp_manager.name = \"fine_tuned\"\n",
        "cfg.exp_manager.use_datetime_version = False\n",
        "cfg.exp_manager.create_tensorboard_logger = False\n",
        "cfg.exp_manager.resume_if_exists = True\n",
        "cfg.exp_manager.resume_ignore_no_checkpoint = True\n",
        "cfg.exp_manager.checkpoint_callback_params.save_best_model = True\n",
        "\n",
        "cfg.model.optim.sched.name = \"CosineAnnealing\"\n",
        "cfg.model.optim.sched.warmup_steps = 500\n",
        "cfg.model.optim.sched.max_steps = 2000\n",
        "cfg.model.optim.sched.min_lr = 0\n",
        "cfg.model.optim.lr = 0.015 #if encoder is frozen, lr can be much higher\n",
        "cfg.model.optim.weight_decay = 0\n",
        "\n",
        "cfg.trainer.max_steps = cfg.model.optim.sched.max_steps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i3-_tFGDNPvZ"
      },
      "source": [
        "In order to load our encoder, we add the following to the config. We need to set init_strict to False, since the decoder for this model will be different, in order to have the correct output for ctc."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3GKv7ERxNPRc"
      },
      "outputs": [],
      "source": [
        "cfg.init_from_nemo_model=data_dir + \"/content/exp/pre_trained/checkpoints/pre_trained.nemo\"\n",
        "cfg.init_strict = False"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MOZmD9sjNgfX"
      },
      "outputs": [],
      "source": [
        "cfg = OmegaConf.to_container(cfg, resolve=True)\n",
        "cfg = OmegaConf.create(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "InacQMmE8tPZ"
      },
      "source": [
        "## Fine-tuning the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l3eNBs_sNhjE"
      },
      "source": [
        "Initializing our model from config:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IEScq3t_vB6N"
      },
      "outputs": [],
      "source": [
        "from nemo.collections.asr.models.ctc_bpe_models import EncDecCTCModelBPE\n",
        "\n",
        "trainer = pl.Trainer(**cfg.trainer)\n",
        "exp_manager(trainer, cfg.get(\"exp_manager\", None))\n",
        "asr_model = EncDecCTCModelBPE(cfg=cfg.model, trainer=trainer)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uif9DLOQ8d0b"
      },
      "source": [
        "Loading our pre-trained checkpoint:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Jes4vqx4vLRC"
      },
      "outputs": [],
      "source": [
        "asr_model.maybe_init_from_pretrained_checkpoint(cfg)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "We can optionally freeze the encoder and only fine-tune the decoder during training. This can be done to lower the memory and time requirements of fine-tuning, but will likely result in a higher word error rate."
      ],
      "metadata": {
        "id": "S5aVb2F8WuAR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#asr_model.encoder.freeze()"
      ],
      "metadata": {
        "id": "LpF_YQUmXUR8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GdoIbsLn8gNC"
      },
      "source": [
        "Now we can run fine-tuning."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "AACa0T6jJtMQ"
      },
      "outputs": [],
      "source": [
        "trainer.fit(asr_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "With the default parameters in this notebook, this pre-training and fine-tuning should achieve around 0.2-0.3 word error rate on the an4 validation set. With frozen encoder and lr increased to 0.15, you will get around 0.6 WER."
      ],
      "metadata": {
        "id": "UfnbNZ-AmmD1"
      }
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "Self_Supervised_Pre_Training.ipynb",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.7"
    },
    "pycharm": {
      "stem_cell": {
        "cell_type": "raw",
        "metadata": {
          "collapsed": false
        },
        "source": []
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}